import 'package:bruno/bruno.dart';
import 'package:common/common.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:miaowu/app/module/tabbar_page/tabbar_page.dart';

import '../login/widget/content_text_field_widget.dart';
import '../login/widget/content_text_widget.dart';
import '../model/register_config.dart';
import '../model/register_config_req.dart';

class UserInfoEditInfoPage extends StatefulWidget {
  const UserInfoEditInfoPage({
    super.key,
    required this.req,
    required this.configModel,
  });
  final RegisterConfigReq req;
  final RegisterConfig configModel;
  @override
  State<UserInfoEditInfoPage> createState() => _UserInfoEditInfoPageState();
}

class _UserInfoEditInfoPageState extends State<UserInfoEditInfoPage> {
  String nickname = ''; //昵称
  String birthday = ''; // 生日
  String constellation = ''; // 星座
  String city = ''; // 出生地址
  String cityname = ''; //
  String pmcode = ''; // 邀请码

  void submitUserInfo() {
    Step3 step3 = widget.configModel.step3!;
    city = '652900';
    if (step3.nickname!.view == 1 && step3.nickname!.need == 1 && nickname.isEmpty) {
      Toast.showText('请输入昵称');
      return;
    }
    if (step3.birthday!.view == 1 && step3.birthday!.need == 1 && birthday.isEmpty) {
      Toast.showText('请设置出生日期');
      return;
    }
    if (step3.area!.view == 1 && step3.area!.need == 1 && city.isEmpty) {
      Toast.showText('请选择您的所在地');
      return;
    }
    if (step3.pmcode!.view == 1 && step3.pmcode!.need == 1 && pmcode.isEmpty) {
      Toast.showText('请输入邀请码');
      return;
    }

    HttpProvider.upload(
      '/user/subInfoInit',
      explain: '用户提交初始化信息',
      paths: {'avatar': widget.req.filePath},
      params: {
        'ifupavatar': 1, // 是否上传了头像 0未传 1已传
        'gender': widget.req.gender, // 性别 1男 2女
        'nickname': nickname, // 昵称
        'birthday': birthday, // 生日yyyy-mm-dd
        'city': city, // 城市ID，6位，不填时传0
        'pmcode': pmcode, // 推广邀请码，默认显示优先级，前端本地pmcode，无值时显示默认文字，不填时传空
      },
      // cancelToken: cancelToken,
      send: (count, total) {
        logs('------------上传进度: $count/$total    -----   ${count / total * 100}%');
      },
      success: (result) {
        Get.offAll(const TabBarPage());
      },
      failure: (result) {
        Toast.showText(result.message);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: SafeArea(
        top: false,
        child: Stack(
          children: [
            Image.asset('assets/app/images/auth/background_top_image.png'),
            Scaffold(
              appBar: BrnAppBar(title: '', backgroundColor: Colors.transparent),
              backgroundColor: Colors.transparent,
              body: Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Column(
                  // mainAxisSize: MainAxisSize.max,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 32.h),
                    Padding(
                      padding: EdgeInsets.only(left: 16.0.w),
                      child: Text(widget.configModel.step3?.maintitle ?? '完成最有一步吧！~',
                          style:
                              TextStyle(color: const Color(0xFF000000), fontSize: 28.sp, fontWeight: FontWeight.w600)),
                    ),
                    SizedBox(height: 40.h),
                    if (widget.configModel.step3?.nickname?.view == 1)
                      ContentTextFieldWidget(
                        hintText: widget.configModel.step3?.nickname?.title ?? '给自己取个昵称吧~',
                        maxLength: (widget.configModel.step3?.nickname?.maxnum ?? 10).toString().toInt(),
                        onChanged: (value) {
                          nickname = value;
                        },
                        onSubmit: (value) {
                          nickname = value;
                        },
                      ),
                    if (widget.configModel.step3?.birthday?.view == 1)
                      ContentTextWidget(
                        hintText: widget.configModel.step3?.birthday?.title ?? '选择您的生日',
                        text: birthday,
                        content: constellation,
                        onTap: () {
                          Birthday birthdayItem = widget.configModel.step3!.birthday!;
                          if (birthdayItem.edit != 1) {
                            return;
                          }
                          String selectTime = widget.req.gender == '1'
                              ? '${birthdayItem.dict!.defaultItem!.maleYear}-${birthdayItem.dict!.defaultItem!.month}-${birthdayItem.dict!.defaultItem!.day}'
                              : '${birthdayItem.dict!.defaultItem!.femaleYear}-${birthdayItem.dict!.defaultItem!.month}-${birthdayItem.dict!.defaultItem!.day}';
                          BottomPickerSheet.showDatePicker(context,
                              title: widget.configModel.step3?.birthday?.title ?? '选择生日',
                              dateType: PickerDateType.YMD,
                              selectTime: DateTimeUtils.getDateTime(selectTime.toString()),
                              maxTime: DateTimeUtils.getDateTime(birthdayItem.dict!.options!.maxyear.toString()),
                              minTime: DateTimeUtils.getDateTime(birthdayItem.dict!.options!.minyear.toString()),
                              clickCallBack: (selectValue, selectIndex) {
                            final date = DateTimeUtils.formatDateStr(selectValue, format: 'yyyy-MM-dd');
                            int age = getAgeFromBirthdayWithSep(date);
                            String constellationStr =
                                getConstellation(DateTimeUtils.getDateTime(selectValue.toString())!);
                            constellation = '$age | $constellationStr';
                            setState(() {
                              birthday = date;
                            });
                          });
                        },
                      ),
                    if (widget.configModel.step3?.area?.view == 1)
                      ContentTextWidget(
                        hintText: widget.configModel.step3?.area?.title ?? '选择您的所在地',
                        text: cityname,
                        onTap: () {
                          _invoke();
                        },
                      ),
                    if (widget.configModel.step3?.pmcode?.view == 1)
                      ContentTextFieldWidget(
                        hintText: widget.configModel.step3?.pmcode?.title ?? '邀请码（选填）',
                        onChanged: (value) {
                          pmcode = value;
                        },
                        onSubmit: (value) {
                          pmcode = value;
                        },
                      ),
                    // const Spacer(),
                  ],
                ),
              ),
              bottomNavigationBar: Padding(
                padding: EdgeInsets.only(left: 20.w, right: 20.w, bottom: Get.bottomBarHeight + 20),
                child: BrnBigMainButton(
                  title: widget.configModel.step3?.btntxt ?? "开启你的喵声之旅".tr,
                  width: double.infinity - 32 * 2,
                  bgColor: const Color(0xFF25D4D0),
                  bgDisEnableColor: const Color(0xFF25D4D0).withOpacity(0.6),
                  themeData: BrnButtonConfig(bigButtonRadius: 255, bigButtonHeight: 45.h, bigButtonFontSize: 16.sp),
                  isEnable: true, // nick.isNotEmpty && birthday.isNotEmpty && adress.isNotEmpty,
                  onTap: () {
                    submitUserInfo();
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _invoke() async {
    Toast.showLoading();
    Result result = await HttpProvider.get('/region/getRegList', explain: '获取区域列表');
    Toast.dismiss();
    if (result.code != 0) {
      Toast.showText(result.message);
      return;
    }
    List<dynamic> list = result.data['data'];
    final res = await showModalBottomSheet<CityResult>(
        context: Get.context!,
        builder: (_) {
          return CityPicker(dataList: list);
        });
    logs(res);
    if (res != null) {
      cityname = '${res.province}-${res.city!}';
      city = res.code.toString();
      setState(() {});
    }
  }
}
